// levelmanager.cpp
#include "levelmanager.h"
#include <QDir>
#include <QFileInfoList>
#include <QDebug>

LevelManager::LevelManager(QObject *parent) : QObject(parent) {}

bool LevelManager::loadLevelList(const QString &directory) {
    m_levelDirectory = directory;
    QDir dir(directory);
    if (!dir.exists()) {
        emit loadFailed("关卡目录不存在: " + directory);
        return false;
    }

    // 获取所有.map文件并按名称排序
    QFileInfoList files = dir.entryInfoList({"*.map"}, QDir::Files, QDir::Name);
    m_levelFiles.clear();

    for (const auto &file : files) {
        m_levelFiles.append(file.filePath());
    }

    if (m_levelFiles.isEmpty()) {
        emit loadFailed("关卡目录中没有找到地图文件");
        return false;
    }

    emit levelChanged(m_currentLevel, m_levelFiles.size());
    return true;
}

bool LevelManager::setLevel(int level) {
    if (level < 0 || level >= m_levelFiles.size()) {
        emit loadFailed("无效的关卡编号");
        return false;
    }

    MapData mapData;
    if (!m_mapManager.loadMapFromFile(m_levelFiles[level], mapData)) {
        emit loadFailed("加载关卡失败: " + m_levelFiles[level]);
        return false;
    }

    m_currentLevel = level;
    emit levelLoaded(mapData);
    emit levelChanged(m_currentLevel, m_levelFiles.size());
    return true;
}

bool LevelManager::nextLevel() {
    if (m_currentLevel + 1 < m_levelFiles.size()) {
        return setLevel(m_currentLevel + 1);
    } else {
        emit loadFailed("已经是最后一关");
        return false;
    }
}

bool LevelManager::prevLevel() {
    if (m_currentLevel > 0) {
        return setLevel(m_currentLevel - 1);
    } else {
        emit loadFailed("已经是第一关");
        return false;
    }
}
